<template>
	<div v-loading="loading">
		<template v-if="!initialLoading || !loading">
			<div v-if="editMode">
				<wt-model-form ref="form" :model="model" v-model="currentValue" @cancel="onCancel" :id="currentId" :params-data="paramsData" @saved="onSaved"></wt-model-form>
			</div>
			<div v-if="!editMode">
				<template v-if="isEmpty">
					<p>{{ query.placeholder }}</p><el-button v-if="allowEdit" type="primary" @click="onSet" icon="plus">添加</el-button>
				</template>
				<template v-else>
					<table class="wt-form">
						<template v-for="(field, index) in fields" v-if="field.display">
							<tr>
								<td class="wt-form-label">{{ field.label }}： </td>
								<td>
									<template v-if="field.customDisplayComponent">
										<component :is="field.customDisplayComponent" :value="currentValue[field.tableName]" :field="field" :current-value="currentValue" :orgin-current-value="orginCurrentValue"></component>
									</template>
									<template v-else-if="field.type == types.images">
										<wt-images 
											:value="currentValue[field.tableName]"
											size="large"
										></wt-images>
									</template>
									<template v-else>
									{{ getDisplay(field) }}
									</template>
								</td>
							</tr>
						</template>
					</table>
					<div v-if="allowEdit" style="float: right">
					<el-button type="primary" @click="onSet" icon="edit">修改</el-button>
					<el-button @click="onDelete" icon="delete" v-if="allowDelet" :loading="deleting">删除</el-button>
					</div>
				</template>
			</div>
		</template>
	</div>
</template>
<script>
	/**
		为单一记录数据模型设计，集成了查询、添加、修改、删除一体的model信息模块。
	 */
	import Vue from 'vue';
	import ElementUI from 'element-ui';
	import ModelUtils from '../utils/wt-model-utils';
	import ModelForm from './wt-model-form';
	import Service from '../utils/wt-model-service';
	import Fields from '../utils/wt-model-field';
	import Images from './wt-images';

	Vue.use(ElementUI);
	Vue.component(ModelForm.name, ModelForm);
	Vue.component(Images.name, Images);

	export default {
		name: 'wt-model-info',
		props: {
			model: Object,
			value: {
				type: Object,
				default: null
			},
			autoLoad: {
				type: Boolean,
				default: false
			},
			// 用于组合extraParams的参数集合
			paramsData: {
				type: Object,
				default: null
			},
			initialLoading: {
				type: Boolean,
				default: false
			},
			allowEdit: {
				type: Boolean,
				default: false
			},
			allowDelet:{
				type: Boolean,
				default: true
			}
		},
		data() {
			return {
				currentValue: this.value,
				//orginCurrentValue存放未经处理过的currentValue
				orginCurrentValue:{},
				extraParams: null,
				loading: this.initialLoading,
				editMode: false,
				currentId: null,
				deleting: false,
				types: Fields.types
			}
		},
		computed: {
			fields: function() {
				return this.model.fields;
			},
			query: function() {
				return this.model.query;
			},
			isEmpty: function() {
				if (this.currentValue == null) {
					return true;
				}
				let type = typeof this.currentValue;
				if (type == 'string') {
					return this.currentValue == '';
				}
				else if (type == 'object') {
					return this.currentValue.length == 0;
				}
				else {
					return this.currentValue == null;
				}
			}
		},
		watch: {
			// 当前数据变化时自动解析id
			'currentValue'(val, oldValue) {
				
				if (val != null && val !== undefined) {
					 let id = ModelUtils.getIdValueFromQueryResult(this.model, val);
					 this.currentId = id;
				}
			},
			'value'(val){				
				this.setCurrentValue(val);
			}
		},
		methods: {
			reset() {
				this.currentValue = null;
				this.currentId = null;
			},
			parseImages(field) {
				let value = this.currentValue[field.tableName];
				if (value) {
					let parsedName = "__" + field.tableName;
					if (typeof value === 'string') {
						value = JSON.parse(value);
					}
					else {
						value = [];
					}
					this.currentValue[parsedName] = value;
				}
			},
			setCurrentValue(value) {
				this.orginCurrentValue = Object.assign({},value)
				this.currentValue = value;				
				if (this.currentValue) {
					ModelUtils.normalizeData(this.model, this.currentValue);
				}
				this.$emit('input', value);
			},
			load() {
				let vm = this;
				// require('winged/utils/axios');
				let caller = null;
				let transfer = this.query.transfer;
				this.loading = true;

				Service.query(this.model, this.extraParams, (data) => {
					this.loading = false;
					data = ModelUtils.parseSingleItemResult(data);
					if(this.model.query.tableName){
						data = data[this.model.query.tableName];
					}
					this.setCurrentValue(data);
				}, (error) =>{
					this.loading = false;
					console.error(error);
					this.$message.error('加载出错');
				});
			},
			edit(data) {
				this.setCurrentValue(data);
				this.onSet();
			},
			onSet() {
				this.editMode = true;
				// 延迟一帧，等value绑定后进行reset
				this.$nextTick(() => {
					this.$refs.form.reset();
				});
			},
			onCancel() {
				this.editMode = false;
			},
			onSaved(data) {
				// 由于有图片上传，目前需要强制加载一次数据
				this.load();
				// this.setCurrentValue(data);
				this.editMode = false;
				this.$emit('count',{model:this.model,data: 1})
			},
			onDelete() {
				let vm = this;
				this.$confirm( '您将删除患者的'+ this.model.title + '，是否确定？', '操作提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.deleting = true;
					Service.remove(this.model, this.currentId, function(data){
						vm.$emit('count',{model:vm.model,data: 0})
						vm.deleting = false;
						vm.reset();
						vm.$message.success('删除成功');
					}, function (error) {
						vm.deleting = false;
						vm.$message.error('删除失败');
					});
				}).catch(() => {
					vm.deleting = false;
				})
			},
			getDisplay(field) {
				return ModelUtils.formatFieldDisplay(this.currentValue, field);
			},
			buildExtraParams() {
				console.log(this.extraParams)
				if (this.extraParams != null) {
					return;
				}
				this.extraParams = ModelUtils.buildQueryExtraParams(this.model.query, this.paramsData);
			},
		},
		created() {
			//如果对本组件传入了value（currentValue），则进行normalizeData处理
			this.orginCurrentValue = Object.assign({},this.currentValue)
			console.log('this.orginCurrentValue',this.orginCurrentValue)
			this.currentValue = !!this.currentValue ? ModelUtils.normalizeData(this.model, this.currentValue) : this.currentValue;
			this.buildExtraParams();
		},
		mounted() {
			if(this.autoLoad && this.currentValue == null) {
				this.load();
			}
		}
	}

</script>